package cn.com.anypay.manager.payment.controller;

import cn.com.anypay.manager.payment.core.PaymentException;
import cn.com.anypay.manager.payment.dto.*;
import cn.com.anypay.manager.payment.manager.PaymentChannelManager;
import cn.com.anypay.manager.payment.service.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付控制器
 *
 * 提供支付相关的REST API接口
 *
 * @author AnyPay Team
 * @version 1.0
 * @since 2025-07-05
 */
@RestController
@RequestMapping("/api/payment")
public class PaymentController {

    private static final Logger logger = LoggerFactory.getLogger(PaymentController.class);

    @Autowired
    private PaymentService paymentService;

    /**
     * 初始化测试渠道
     */
    @PostMapping("/init")
    public Map<String, Object> initializeChannels() {
        Map<String, Object> response = new HashMap<>();

        try {
            paymentService.initializeTestChannels();

            response.put("success", true);
            response.put("message", "测试渠道初始化成功");
            response.put("channels", paymentService.getAllChannelInfo());

        } catch (Exception e) {
            logger.error("初始化测试渠道失败", e);
            response.put("success", false);
            response.put("message", "初始化失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 创建支付
     */
    @PostMapping("/create")
    public Map<String, Object> createPayment(@RequestBody PaymentRequestDTO request) {
        Map<String, Object> response = new HashMap<>();

        try {
            PaymentResultDTO result = paymentService.createPayment(request);

            response.put("success", true);
            response.put("message", "支付创建成功");
            response.put("data", result);

        } catch (PaymentException e) {
            logger.error("支付创建失败", e);
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("message", e.getMessage());
            response.put("channelId", e.getChannelId());
        } catch (Exception e) {
            logger.error("支付创建异常", e);
            response.put("success", false);
            response.put("message", "系统异常: " + e.getMessage());
        }

        return response;
    }

    /**
     * 查询支付状态
     */
    @PostMapping("/query")
    public Map<String, Object> queryPayment(@RequestBody QueryRequestDTO request) {
        Map<String, Object> response = new HashMap<>();

        try {
            QueryResultDTO result = paymentService.queryPayment(request);

            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", result);

        } catch (PaymentException e) {
            logger.error("支付查询失败", e);
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("message", e.getMessage());
            response.put("channelId", e.getChannelId());
        } catch (Exception e) {
            logger.error("支付查询异常", e);
            response.put("success", false);
            response.put("message", "系统异常: " + e.getMessage());
        }

        return response;
    }

    /**
     * 关闭支付
     */
    @PostMapping("/close")
    public Map<String, Object> closePayment(@RequestParam String channelId, @RequestParam String orderId) {
        Map<String, Object> response = new HashMap<>();

        try {
            boolean result = paymentService.closePayment(channelId, orderId);

            response.put("success", result);
            response.put("message", result ? "支付关闭成功" : "支付关闭失败");

        } catch (PaymentException e) {
            logger.error("支付关闭失败", e);
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("message", e.getMessage());
            response.put("channelId", e.getChannelId());
        } catch (Exception e) {
            logger.error("支付关闭异常", e);
            response.put("success", false);
            response.put("message", "系统异常: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理支付回调
     */
    @PostMapping("/callback/{channelId}")
    public Map<String, Object> processCallback(@PathVariable String channelId, @RequestBody String callbackData) {
        Map<String, Object> response = new HashMap<>();

        try {
            PaymentResultDTO result = paymentService.processCallback(channelId, callbackData);

            response.put("success", true);
            response.put("message", "回调处理成功");
            response.put("data", result);

        } catch (PaymentException e) {
            logger.error("回调处理失败", e);
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("message", e.getMessage());
            response.put("channelId", e.getChannelId());
        } catch (Exception e) {
            logger.error("回调处理异常", e);
            response.put("success", false);
            response.put("message", "系统异常: " + e.getMessage());
        }

        return response;
    }

    /**
     * 获取所有渠道信息（包括多实现）
     */
    @GetMapping("/channels")
    public Map<String, Object> getAllChannels() {
        Map<String, Object> response = new HashMap<>();

        try {
            PaymentChannelManager.EnhancedChannelInfo[] channels = paymentService.getAllEnhancedChannelInfo();

            response.put("success", true);
            response.put("message", "获取渠道信息成功");
            response.put("data", channels);
            response.put("count", channels.length);

        } catch (Exception e) {
            logger.error("获取渠道信息失败", e);
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 获取指定渠道信息
     */
    @GetMapping("/channels/{channelId}")
    public Map<String, Object> getChannelInfo(@PathVariable String channelId) {
        Map<String, Object> response = new HashMap<>();

        try {
            PaymentChannelManager.ChannelInfo channelInfo = paymentService.getChannelInfo(channelId);

            if (channelInfo != null) {
                response.put("success", true);
                response.put("message", "获取渠道信息成功");
                response.put("data", channelInfo);
            } else {
                response.put("success", false);
                response.put("message", "渠道不存在: " + channelId);
            }

        } catch (Exception e) {
            logger.error("获取渠道信息失败", e);
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 获取渠道支持的支付产品
     */
    @GetMapping("/channels/{channelId}/pay-methods")
    public Map<String, Object> getSupportedPayMethods(@PathVariable String channelId) {
        Map<String, Object> response = new HashMap<>();

        try {
            String[] payMethods = paymentService.getSupportedPayMethods(channelId);

            response.put("success", true);
            response.put("message", "获取支付产品成功");
            response.put("data", payMethods);

        } catch (PaymentException e) {
            logger.error("获取支付产品失败", e);
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("message", e.getMessage());
            response.put("channelId", e.getChannelId());
        } catch (Exception e) {
            logger.error("获取支付产品异常", e);
            response.put("success", false);
            response.put("message", "系统异常: " + e.getMessage());
        }

        return response;
    }

    /**
     * 获取渠道配置模板
     */
    @GetMapping("/channels/{channelId}/config-template")
    public Map<String, Object> getChannelConfigTemplate(@PathVariable String channelId) {
        Map<String, Object> response = new HashMap<>();

        try {
            String template = paymentService.getChannelConfigTemplate(channelId);

            response.put("success", true);
            response.put("message", "获取配置模板成功");
            response.put("data", template);

        } catch (PaymentException e) {
            logger.error("获取配置模板失败", e);
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("message", e.getMessage());
            response.put("channelId", e.getChannelId());
        } catch (Exception e) {
            logger.error("获取配置模板异常", e);
            response.put("success", false);
            response.put("message", "系统异常: " + e.getMessage());
        }

        return response;
    }

    /**
     * 测试支付 - 快速创建测试订单
     */
    @PostMapping("/test1")
    public Map<String, Object> testPayment(@RequestParam String channelId, @RequestParam String payMethod) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 创建测试支付请求
            PaymentRequestDTO request = new PaymentRequestDTO(
                "TEST_ORDER_" + System.currentTimeMillis(),
                channelId,
                payMethod,
                new BigDecimal("100.00"),
                "测试商品"
            );
            request.setUserIp("127.0.0.1");
            request.setNotifyUrl("http://localhost:8080/api/payment/callback/" + channelId);

            PaymentResultDTO result = paymentService.createPayment(request);

            response.put("success", true);
            response.put("message", "测试支付创建成功");
            response.put("data", result);

        } catch (PaymentException e) {
            logger.error("测试支付失败", e);
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("message", e.getMessage());
            response.put("channelId", e.getChannelId());
        } catch (Exception e) {
            logger.error("测试支付异常", e);
            response.put("success", false);
            response.put("message", "系统异常: " + e.getMessage());
        }

        return response;
    }

    /**
     * 获取渠道的实现类型列表
     */
    @GetMapping("/channels/{channelId}/implementations")
    public Map<String, Object> getChannelImplementations(@PathVariable String channelId) {
        Map<String, Object> response = new HashMap<>();

        try {
            String[] implementations = paymentService.getChannelImplementationTypes(channelId);
            String defaultImpl = paymentService.getChannelDefaultImplementation(channelId);

            response.put("success", true);
            response.put("message", "获取渠道实现信息成功");
            response.put("data", Map.of(
                "channelId", channelId,
                "implementations", implementations,
                "defaultImplementation", defaultImpl,
                "implementationCount", implementations.length,
                "hasMultipleImplementations", implementations.length > 1
            ));

        } catch (Exception e) {
            logger.error("获取渠道实现信息失败", e);
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 获取所有渠道的实现信息
     */
    @GetMapping("/channels/implementations")
    public Map<String, Object> getAllChannelImplementations() {
        Map<String, Object> response = new HashMap<>();

        try {
            Map<String, PaymentService.ChannelImplementationInfo> allInfo = paymentService.getAllChannelImplementationInfo();

            response.put("success", true);
            response.put("message", "获取所有渠道实现信息成功");
            response.put("data", allInfo);
            response.put("count", allInfo.size());

            // 打印到日志
            logger.info("=== API请求 - 所有渠道实现信息 ===");
            for (Map.Entry<String, PaymentService.ChannelImplementationInfo> entry : allInfo.entrySet()) {
                PaymentService.ChannelImplementationInfo info = entry.getValue();
                logger.info("渠道: {}", info.getChannelId());
                logger.info("  支持的实现类型: {}", String.join(", ", info.getImplementations()));
                logger.info("  默认实现: {}", info.getDefaultImplementation());
                logger.info("  实现数量: {}", info.getImplementationCount());
                logger.info("  是否支持多实现: {}", info.hasMultipleImplementations());
                logger.info("---");
            }

        } catch (Exception e) {
            logger.error("获取所有渠道实现信息失败", e);
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 打印所有渠道实现信息到日志
     */
    @PostMapping("/channels/implementations/print")
    public Map<String, Object> printAllChannelImplementations() {
        Map<String, Object> response = new HashMap<>();

        try {
            paymentService.printAllChannelImplementationInfo();

            response.put("success", true);
            response.put("message", "渠道实现信息已打印到日志");

        } catch (Exception e) {
            logger.error("打印渠道实现信息失败", e);
            response.put("success", false);
            response.put("message", "打印失败: " + e.getMessage());
        }

        return response;
    }
}